package com.PlantVsZombies.db.dao;

import java.sql.SQLException;
import java.util.Date;

import javax.swing.JOptionPane;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.PlantVsZombies.db.model.Player;
import com.PlantVsZombies.util.DBUtil;

public class PlayerDao {

	QueryRunner qr = new QueryRunner(DBUtil.getDataSource());

	public boolean insertPlayer(Player player) {
		String sql = "insert into t_player(name, time) values(?,?)";
		Object[] params = { player.getName(), new Date() };
		try {
			return qr.update(sql, params) > 0;
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "插入玩家信息失败");
			System.out.println("插入玩家信息失败");
			return false;
		}
	}

	public Player select(String name) {
		String sql = "select * from t_player where name='" + name + "'";
		try {
			return (Player) qr.query(sql, new BeanHandler(Player.class));
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "数据库服务未开启");
			System.out.println("查询玩家出错");
			return null;
		}
	}
	
	public Player selectLast() {
		String sql = "select * from t_player ORDER BY time desc LIMIT 1";
		try {
			return (Player) qr.query(sql, new BeanHandler(Player.class));
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "数据库服务未开启");
			System.out.println("查询玩家出错");
			return null;
		}
	}
}
